package com.gitee.fantaros.web.fan.netcut.threading;


import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

@Component
public class AsyncProcessManager {

    public <T> void async(Awaitable<T, String> awaitable, ResultCallback<T> resultCallback, Processable<String> processable) {
        DefaultAsyncable<T> defaultAsyncable = new DefaultAsyncable<>(awaitable);
        defaultAsyncable.setProcessable(processable);
        defaultAsyncable.setResultCallback(resultCallback);
        ThreadPoolUtil.executeOnThreadPool(defaultAsyncable);
    }

    public static class DefaultAsyncable<T> implements Asyncable<T, String> {
        @Getter
        @Setter
        private Processable<String> processable;
        @Getter
        @Setter
        private ResultCallback<T> resultCallback;

        private final Awaitable<T, String> awaitable;

        public DefaultAsyncable(Awaitable<T, String> awaitable) {
            this.awaitable = awaitable;
        }

        @Override
        public void run() {
            try {
                awaitable.await(resultCallback, processable);
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
    }

}
